﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WGM_Silverlight.Views;
using WGM_Silverlight.Classes;
using System.Windows.Media.Imaging;
using System.Text.RegularExpressions;
using System.Windows.Browser;

namespace WGM_Silverlight.Controls
{
    public partial class ChatControl : UserControl
    {
        public bool IsMainWindow { get; set; }
        private string _username;
        private MainView _parent;
        public bool HasImage { get; set; }
        public ImageSource ContactImageSource 
        {
            get { return _contactImageBrush.ImageSource; }
        }
        public ChatControl(string username,  MainView parent)
        {
            InitializeComponent();
            _username = username;
            _parent = parent;
            _incomingMessageScroller.SetIsMouseWheelScrollingEnabled(true);
            _outgoingMessageScroller.SetIsMouseWheelScrollingEnabled(true);
            
        }
        public void SetContactInfo(ContactInfo contactInfo)
        {
            _contactNameTb.Text = contactInfo.ContactDisplayName;
            _contactStatusTb.Text = contactInfo.ContactDisplayStatus;
            if (contactInfo.ContactUserOptions != null)
            {
                ToolTipService.SetToolTip(_contactInfoPanel, HelperFunctions.GetCLToolTip(contactInfo.ContactUserOptions));
            }
        }
        public void SetContactImage(ImageSource source)
        {
            _contactImageBrush.ImageSource = source;
            _largeDispayImageBrush.ImageSource = source;
            HasImage = true;
        }
        public void SetOutgoingTextOptions(ContactInfo contactInfo)
        {
            _outgoingTb.Foreground = new SolidColorBrush( HelperFunctions.GetContactColour(contactInfo.ContactUserOptions));
            _outgoingTb.FontFamily = new FontFamily(contactInfo.ContactUserOptions.UserFontFace);
            _outgoingTb.FontSize = contactInfo.ContactUserOptions.FontSize;
            _outgoingTb.FontStyle = HelperFunctions.GetFontStyle(contactInfo.ContactUserOptions);
            _outgoingTb.FontWeight = HelperFunctions.GetFontWeight(contactInfo.ContactUserOptions);
        }
        public string Username
        {
            get { return _username; }
        }
        private void OnOutgoingKeyUp(object sender, KeyEventArgs e)
        {            
            if (e.Key == Key.Enter)
            {
                if (_outgoingTb.Text.Trim() != "")
                {
                    _parent.SendMessage(_username, _outgoingTb.Text.Trim(), this);
                    _outgoingTb.Text = "";
                }
                return;
            }

            _outgoingMessageScroller.UpdateLayout();            
            _outgoingMessageScroller.ScrollToBottom();
        }
        public void RecieveMessage(ContactInfo sender, WGM_Svc.WGMMessage message, bool isFailed)
        {
            TextBlock introBlock = new TextBlock();
            introBlock.FontFamily = new FontFamily("Verdana");
            introBlock.Foreground = new SolidColorBrush(Colors.Gray);
            introBlock.FontStyle = FontStyles.Italic;
            introBlock.Text ="<"+message.TimeStamp.ToString()+">"+ HelperFunctions.GetIntroString(sender.ContactUserOptions)+ " says";
            introBlock.TextWrapping = TextWrapping.Wrap;

            if (isFailed)
            {
                introBlock.Foreground = new SolidColorBrush(Colors.Red);
                introBlock.Text = "<" + message.TimeStamp.ToString() + "> Unable to send message:";

            }
            _incomingBlocks.Children.Add(introBlock);


            TextBox messageBlock = new TextBox();
            messageBlock.FontStyle = HelperFunctions.GetFontStyle(sender.ContactUserOptions);
            messageBlock.FontWeight = HelperFunctions.GetFontWeight(sender.ContactUserOptions);
            messageBlock.Foreground = new SolidColorBrush(HelperFunctions.GetContactColour(sender.ContactUserOptions));
            messageBlock.FontFamily = new FontFamily(sender.ContactUserOptions.UserFontFace);
            messageBlock.FontSize = sender.ContactUserOptions.FontSize;
            messageBlock.Text = message.Message as string;
            messageBlock.TextWrapping = TextWrapping.Wrap;
            messageBlock.BorderThickness = new Thickness(0);
            _incomingBlocks.Children.Add(messageBlock);

            if (isFailed)
            {
                TextBlock linkBlock = new TextBlock();

                linkBlock.FontFamily = new FontFamily("Verdana");
                linkBlock.Foreground = new SolidColorBrush(Colors.Gray);
                linkBlock.FontStyle = FontStyles.Italic;
                linkBlock.Text = "Click here to resend";
                linkBlock.Tag = message;
                linkBlock.Cursor = Cursors.Hand;
                linkBlock.MouseLeftButtonDown += new MouseButtonEventHandler(linkBlock_MouseLeftButtonDown);
                linkBlock.TextWrapping = TextWrapping.Wrap;
                _incomingBlocks.Children.Add(linkBlock);
            }
            else
            {
                Regex linkMatch = new Regex("(?:^|[\\s\\[\\]\\}\\{\\(\\)\\\'\\\"<>])((?:(?:https?|gopher|ftp|file|irc):\\/\\/|www\\.)[a-zA-Z0-9\\.\\-=;&%\\?]+(?:\\/?[a-zA-Z0-9\\.\\-=;:'{}><,~`*_#$+&%\\?]*)*)");
                MatchCollection matches = linkMatch.Matches(message.Message as string);
                if (matches.Count > 0)
                {
                    TextBlock linkBlock = new TextBlock();

                    linkBlock.FontFamily = new FontFamily("Verdana");
                    linkBlock.Foreground = new SolidColorBrush(Colors.Gray);
                    linkBlock.FontStyle = FontStyles.Italic;
                    linkBlock.Text = "Contained Links: ";
                    linkBlock.TextWrapping = TextWrapping.Wrap;
                    _incomingBlocks.Children.Add(linkBlock);
                    foreach (Match link in matches)
                    {
                        TextBlock hlink = new TextBlock();
                        string linkUri = link.Value.ToLower().Trim();

                        hlink.Text = link.Value.Trim();
                        if (!linkUri.StartsWith("http") && !linkUri.StartsWith("https") && !linkUri.StartsWith("ftp"))
                            linkUri = "http://" + linkUri;
                        hlink.Tag = linkUri;
                        hlink.FontFamily = new FontFamily("Verdana");
                        hlink.Foreground = new SolidColorBrush(Colors.Blue);
                        hlink.Cursor = Cursors.Hand;
                        hlink.MouseLeftButtonDown += new MouseButtonEventHandler(hlink_MouseLeftButtonDown);
                        _incomingBlocks.Children.Add(hlink);
                    }
                }
            }
            _incomingMessageScroller.UpdateLayout();
            if (_autoScrollCheck.IsChecked.Value == true)
                _incomingMessageScroller.ScrollToBottom();

        }

        void linkBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            WGM_Svc.WGMMessage message = (sender as TextBlock).Tag as WGM_Svc.WGMMessage;
            _parent.SendMessage(_username, message.Message as string, this);
        }
        void hlink_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock hlink = sender as TextBlock;

            HtmlPage.Window.Eval("window.open('"+hlink.Tag as string+"'), _blank"); 
        }
        internal void ClearContactImage()
        {
            _contactImageBrush.ImageSource = new BitmapImage(new Uri("../Images/blank.png", UriKind.RelativeOrAbsolute));
            HasImage = false;
        }

        private void OnClearMessages(object sender, MouseButtonEventArgs e)
        {
            _incomingBlocks.Children.Clear();
            _incomingMessageScroller.UpdateLayout();
            _incomingMessageScroller.ScrollToTop();
            _incomingMessageScroller.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            _incomingMessageScroller.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
        }

        private void OnContactInfoMouseEnter(object sender, MouseEventArgs e)
        {
            ShowLargeImage();
        }

        private void OncontactInfoMouseLeave(object sender, MouseEventArgs e)
        {
            HideLargeImage();
        }

        internal void ShowLargeImage()
        {
            if (HasImage)
                _animEnter.Begin();
        }

        internal void HideLargeImage()
        {
            if (HasImage)
                _animLeave.Begin();
        }
    }
}
